import modelExtend from 'dva-model-extend'
import api from 'api'
import { pathMatchRegexp } from 'utils'
import { pageModel } from 'utils/model'
import { message } from 'antd'

const { queryauths, setauths } = api

export default modelExtend(pageModel, {
  namespace: 'auths',

  state: {
    data: {},
    select: '',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        let match = pathMatchRegexp('*/auths/authset', location.pathname)
        // console.log("match:" + match);
        // console.log("location.pathname:" + location.pathname);
        if (match) {
          dispatch({
            type: 'setSelect',
            payload: location.query.select,
          })
          dispatch({
            type: 'query',
            payload: {
              ...location.query,
            },
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put, select }) {
      const { result } = yield call(queryauths, payload)
      const selectstate = yield select(_ => _.auths.select)
      yield put({
        type: 'setAuths',
        payload: result,
      })
      yield put({
        type: 'setSelect',
        payload:
          selectstate == '' || selectstate == undefined
            ? result.keys[0]
            : selectstate,
      })
    },
    *setauths({ payload }, { call }) {
      message.loading('修改中...', 0)
      yield call(setauths, payload)
      message.destroy()
      message.success('修改成功')
    },
    *getallauths({ payload }, { call, put, select }) {
      const data = yield call(setauths, payload)
    },
  },

  reducers: {
    setSelect(state, { payload }) {
      state.select = payload
    },
    setAuths(state, { payload }) {
      state.data = payload
    },
  },
})
